# -*- coding:utf-8 -*-
import os
from os import path
from datetime import date,timedelta
import configparser as conf


workspace_config_file_name="workspace.ini"
workspace_config_section="workspace"

def get_workspace_properties_file():
    filepath = os.environ["JOB_PROP_FILE"]
    base_dir=path.dirname(filepath)
    file_name=workspace_config_file_name
    return path.join(base_dir,file_name)


def get_workspace_properties(resultDic):
    if path.exists(get_workspace_properties_file()):
        workspace_config=conf.ConfigParser()
        workspace_config.read(get_workspace_properties_file())
        for key,value in workspace_config.items(workspace_config_section):
            resultDic[key]=value
    print resultDic
    return resultDic

def get_global_properties():
    filepath = os.environ["JOB_PROP_FILE"]
    resultDic = {}
    print "JOB_PROP_FILE  is :", filepath

    with open(filepath, 'r') as f:
        for line in f:
            if line.startswith("#"):
                continue
            else:
                kv = line.split("=")
                key = kv[0].strip().replace('\:',':')
                value = kv[1].strip().replace('\:',':')
                resultDic[key]=value
    resultDic=get_workspace_properties(resultDic)
    return resultDic

def put_value_to_global_properties(resultDic):
    filepath=os.environ["JOB_OUTPUT_PROP_FILE"]
    print "JOB_PROP_FILE  is :", filepath
    str1="{"
    for (name,value) in resultDic.items():
        str1=str1+"\""+name+"\":\""+value+"\","
    str1=str1[:-1]
    str1=str1+"}"
    print "write value : "+ str1
    with open(filepath,'r+') as f:
        f.write(str1)

    workspace_config=conf.ConfigParser()

    if path.exists(get_workspace_properties_file()):
        workspace_config.read(get_workspace_properties_file())
    if workspace_config.has_section(workspace_config_section) == False:
        workspace_config.add_section(workspace_config_section)
    for key in resultDic:
        value=str(resultDic[key])
        workspace_config.set(workspace_config_section,key,value)
    workspace_config.write(open(get_workspace_properties_file(),"w"))

def get_partition_by_flow_type(flow_type,global_properties):
    if flow_type == 'yestoday':
        return (date.today()-timedelta(days=1)).strftime("%Y-%m-%d")
    if flow_type == 'today' :
        return date.today().strftime("%Y-%m-%d")
    if flow_type == 'special_day' :
        return global_properties['special_day']

def get_special_day_raw_data_path(global_properties):
    return global_properties['special_hdfs_path']

